package com.crocodileq.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.crocodileq.dto.LoginFormDTO;
import com.crocodileq.dto.Result;
import com.crocodileq.dto.UserDTO;
import com.crocodileq.entity.User;
import com.crocodileq.entity.UserInfo;
import com.crocodileq.service.IUserInfoService;
import com.crocodileq.service.IUserService;
import com.crocodileq.utils.RedisConstants;
import com.crocodileq.utils.RegexUtils;
import com.crocodileq.utils.SystemConstants;
import com.crocodileq.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.crocodileq.utils.RedisConstants.LOGIN_CODE_KEY;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private IUserInfoService userInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送手机验证码
     */
    @PostMapping("code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        //  发送短信验证码并保存验证码
        //1、校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }

        //2、生成验证码
        Random random = new Random();
        int code = random.nextInt(900000) + 100000;
        //3、redis保存验证码,并设置有效期
        stringRedisTemplate.opsForValue()
                .set(RedisConstants.LOGIN_CODE_KEY + phone,String.valueOf(code),
                        RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4、返回验证码
        log.info("发送验证码成功，验证码：{}", code);
        return Result.ok();
    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session){
        //  实现登录功能
        //1、验证手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号格式错误");
        }
        //2、根据手机号查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, loginForm.getPhone());
        User user = userService.getOne(queryWrapper);
        //3、不存在，创建新用户
        if(Objects.isNull(user)){
            user = createNewUser(loginForm);
        }
        //4、保存用户信息到redis中，生成随机token
        String token = UUID.randomUUID().toString(true);
        String key = RedisConstants.LOGIN_USER_KEY + token;

        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, value) -> value.toString()));

        stringRedisTemplate.opsForHash().putAll(key, userMap);

        //5、存活时间
        stringRedisTemplate.expire(
                key,
                RedisConstants.LOGIN_USER_TTL,
                TimeUnit.MINUTES);

        return Result.ok(token);
    }

    private User createNewUser(LoginFormDTO loginForm) {
        User user = new User();
        user.setPhone(loginForm.getPhone());
        //随机生成6位字符
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(6));
        userService.save(user);

        return user;
    }

    /**
     * 登出功能
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        //  实现登出功能
        //1、获取token
        String token = request.getHeader("Authorization");
        if (token == null) {
            return Result.fail("未登录");
        }
        //2、删除redis中的数据
        stringRedisTemplate.delete(RedisConstants.LOGIN_USER_KEY + token);
        //3、删除threadLocal中的用户信息
        UserHolder.removeUser();
        return Result.ok();
    }

    @GetMapping("/me")
    public Result me(){
        //  获取当前登录的用户并返回
        UserDTO user = UserHolder.getUser();

        return Result.ok(user);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId){
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }
}
